/**
 * 这是一个专门用于权限验证的button
 * dispatch 需要调用的model方法
 */
import React from 'react';
import { connect } from 'dva';
import { Menu, Icon } from 'antd';
import routerDef from 'utils/routerDef';
const MenuItem = Menu.Item;
const { SubMenu } = Menu;
@connect(({ auth, common }) => ({
  authentication: auth.authentication,
  authenticationTree: auth.authenticationTree,
  menuState: common.menuState
}))
class Lmenu extends React.PureComponent {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'auth/getAuthentication',
      payload: {}
    });

    dispatch({
      type: 'common/getMenuState',
      payload: {}
    });
  }

  onTitleClick = (obj) => {
    console.log("点击了SubMenu", obj);
    const { dispatch } = this.props;
    dispatch({
      type: 'common/setMenuState',
      payload: {
        open: obj.key,
        selected: ""
      }
    });
  }

  onMenuItemClick = (menuItem) => {
    routerDef.push(menuItem.url);
    const { dispatch } = this.props;
    dispatch({
      type: 'common/setMenuState',
      payload: {
        open: "",
        selected: menuItem.url
      }
    });

    dispatch({
      type: 'common/setBreadState',
      payload: menuItem
    });

  }

  render() {
    const { authentication, authenticationTree, menuState } = this.props;
    const { onTitleClick, onMenuItemClick } = this;
    return (<Menu theme="dark" openKeys={menuState.open} selectedKeys={menuState.selected} mode="inline">
      {authenticationTree.map(value => (GenMenuShow(value, onTitleClick, onMenuItemClick)))}
    </Menu>);
  }
}

export default Lmenu;

function GenMenuShow(menuItem, onTitleClick, onMenuItemClick) {
  if (menuItem.menu_type == "M" || menuItem.menu_type == "C") {
    let SubMenuStatus = false;
    if (menuItem.children) {
      let children = menuItem.children;
      for (var i = 0; i < children.length; i++) {
        if (children[i].menu_type == "M" || children[i].menu_type == "C") {
          SubMenuStatus = true;
          break;
        }
      }
    }
    if (SubMenuStatus) {
      return (<SubMenu
        key={menuItem.perms}
        onTitleClick={(obj) => { onTitleClick(obj) }}
        title={
          <span>
            <Icon type={menuItem.icon} />
            <span>{menuItem.menu_name}</span>
          </span>
        }
      >{menuItem.children.map(value => { return GenMenuShow(value, onTitleClick, onMenuItemClick) })}</SubMenu>)
    } else {
      return (<MenuItem key={menuItem.url} onClick={() => { onMenuItemClick(menuItem) }}>
        {menuItem.icon && <Icon type={menuItem.icon} />}
        <span>{menuItem.menu_name}</span>
      </MenuItem>);
    }
  }
}